package core

import (
	"context"
	"github.com/kataras/golog"
	"ntrace/utils/routines"
	"syscall"
	"time"
)

type Agent interface {
	GetName() string
	StartAgent() error
	StopAgent()
}

type BaseAgent struct {
	Name       string
	Task       *TraceTask
	Sender     Sender
	Receiver   Receiver
	Aggregator *Aggregator
	Printer    *Printer

	Ctx        context.Context
	CancelFunc context.CancelFunc
}

func (p *BaseAgent) GetName() string {
	return p.Name
}

func (p *BaseAgent) StartAgent() error {

	err := p.Receiver.StartReceiver()
	if err != nil {
		golog.Debugf("start receiver failed. err: %+v", err)
		return err
	}
	err = p.Aggregator.StartAggregate()
	if err != nil {
		golog.Debugf("start aggregator failed. err: %+v", err)
		return err
	}
	err = p.Printer.StartPrint()
	if err != nil {
		golog.Debugf("start printer failed. err: %+v", err)
		return err
	}
	err = p.Sender.StartSender()
	if err != nil {
		golog.Debugf("start sender failed. err: %+v", err)
		return err
	}

	return nil
}

func (p *BaseAgent) StopAgent() {
	if p.CancelFunc != nil {
		p.CancelFunc()
	}
}

func TrigExit(delayMs int64) {
	time.Sleep(time.Duration(delayMs) * time.Millisecond)
	for i := 0; i < 3; i++ {
		err := routines.TrigSignal(syscall.SIGINT)
		if err == nil {
			break
		}
	}
}
